package middleware

import (
	"ginblog/api/common"
	"ginblog/tools/jwt"
	"ginblog/utils/errmsg"
	"github.com/gin-gonic/gin"
	"strings"
)

func JwtToken() gin.HandlerFunc {
	return func(c *gin.Context) {
		token := c.Request.Header.Get("Authorization")
		//token不能为空
		if token == "" {
			common.FailJson(c, errmsg.ERROR_TOKEN_EXIST)
			c.Abort()
			return
		}
		//token 不能为空
		checkToken := strings.Split(token, " ")
		if len(checkToken) == 0 {
			common.FailJson(c, errmsg.ERROR_TOKEN_TYPE_WRONG)
			c.Abort()
			return
		}
		//token 长度是二 第一个结果不能是bearer
		if len(checkToken) != 2 || checkToken[0] != "Bearer" {
			common.FailJson(c, errmsg.ERROR_TOKEN_TYPE_WRONG)
			c.Abort()
			return
		}
		errCode, claims := jwt.ParserToken(checkToken[1])
		if errCode != 0 {
			common.SuccessJson(c, errmsg.ERROR, errmsg.GetErrMsg(errCode))
			c.Abort()
			return
		}
		c.Set("blog_id", claims.Id)
		c.Next()

	}
}
